<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图 -->
    <el-card>
      <el-alert
        class="el-icon-warning"
        title="注意: 只允许为第三级分类设置相关参数！"
        type="warning"
      >
      </el-alert>
      <div style="margin-top: 20px">
        选择商品分类:
        <!-- v-model 双向数据绑定 控制级联选择器选中的值 -->
        <!-- options 数据 -->
        <!-- props label 渲染的字段  value 用户选中的数据 和v-model配合使用 -->
        <el-cascader
          v-model="cascaderValue"
          :options="cateList"
          :props="{
            expandTrigger: 'hover',
            label: 'cat_name',
            value: 'cat_id',
          }"
          @change="handleChange"
        ></el-cascader>
      </div>
      <!-- 动态参数 静态属性选项卡 -->
      <el-tabs v-model="activeName" @tab-click="tabHandleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="cascaderValue.length !== 3"
            @click="addParams"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyData" border>
            <el-table-column type="expand">
              <template slot-scope="{ row }">
                <el-tag
                  closable
                  v-for="(item, i) in row.attr_vals"
                  :key="i"
                  @close="removeClose(row, i)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入框和按钮切换 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="分类名称">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row }">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParams(row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="cascaderValue.length !== 3"
            @click="addParams"
            >添加属性</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="onlyData" border>
            <el-table-column type="expand">
              <template slot-scope="{ row }">
                <el-tag
                  closable
                  v-for="(item, i) in row.attr_vals"
                  :key="i"
                  @close="removeClose(row, i)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入框和按钮切换 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="分类名称">
            </el-table-column>
            <el-table-column label="操作">
              <template>
                <el-button type="primary" icon="el-icon-edit" size="mini"
                  >编辑</el-button
                >
                <el-button type="danger" icon="el-icon-delete" size="mini"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数/添加属性 -->
    <el-dialog
      :title="'添加' + addParamsText"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="$refs.addFormRef.resetFields()"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item :label="addParamsText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPraamsBtn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑动态静态框 -->
    <el-dialog
      @close="$refs.editParamsForm.resetFields()"
      :title="'添加' + addParamsText"
      :visible.sync="editParamsDialogVisible"
      width="50%"
    >
      <el-form
        ref="editParamsForm"
        :model="editForm"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item label="活动名称" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsFrom">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 控制tag
      inputVisible: false,
      inputValue: '',
      // 获取商品分类的数据传入cateList
      cateList: [],
      // input 选中的数组
      cascaderValue: [],
      activeName: 'many',
      // 动态参数数据
      manyData: [],
      // 静态属性数据
      onlyData: [],
      // 对话框默认属性
      addParamsDialogVisible: false,
      editParamsDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      editForm: {
        attr_name: ''
      },
      // 校验规则
      rules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ]
      }
    }
  },

  created() {
    this.getParamsList()
  },
  // 根据某个数据返回新的数据 依赖的数据发生变化会重新计算进行缓存
  computed: {
    // 三级分类id
    cateId() {
      if (this.cascaderValue.length !== 3) return null
      return this.cascaderValue[2]
    },
    addParamsText() {
      return this.activeName === 'only' ? '静态属性' : '动态参数'
    }
  },

  methods: {
    // 获取商品分类数据
    async getParamsList() {
      const res = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    async getParams() {
      if (this.cascaderValue.length !== 3) {
        this.$message.error('选择三级分类')
        this.cascaderValue = []
        this.manyData = []
        this.onlyData = []
        return
      }
      // console.log(this.cateId)
      const res = await this.$axios.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // console.log(res.data)
      // 保存数据
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
    },
    // 级联选择器发生变化
    handleChange() {
      this.getParams()
      // console.log(this.cascaderValue)
    },
    tabHandleClick() {
      this.getParams()
      // console.log(this.activeName)
    },
    addParams() {
      this.addParamsDialogVisible = true
    },
    addPraamsBtn() {
      this.$refs.addFormRef.validate(async flag => {
        if (!flag) return
        // id:this.cateId()
        // this.addForm.attr_name
        // this.activeName
        const res = await this.$axios.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addParamsDialogVisible = false
        this.getParams()
      })
    },
    // 点击编辑按钮
    editParams(row) {
      this.editForm.attr_name = row.attr_name
      this.editForm.attr_id = row.attr_id
      this.editParamsDialogVisible = true
    },
    editParamsFrom() {
      this.$refs.editParamsForm.validate(async flag => {
        if (!flag) return
        const res = await this.$axios.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id},`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParams()
        this.editParamsDialogVisible = false
      })
    },
    // 删除
    deleteParams(row) {
      // console.log('1')
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await this.$axios.delete(
            `categories/${this.cateId}/attributes/${row.attr_id}`
          )
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.getParams()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // tag输入框失去焦点
    async handleInputConfirm(row) {
      if (row.inputValue.trim() === '') {
        row.inputVisible = false
        return
      }

      row.attr_vals.push(row.inputValue)
      const res = await this.$axios.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.status)
      this.$message.success(res.meta.msg)
      // 清空输入框
      row.inputValue = ''
      row.inputVisible = false
      console.log(res)
    },
    // 删除tag
    async removeClose(row, i) {
      console.log(row, i)
      row.attr_vals.splice(i, 1)
      const res = await this.$axios.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.status)
      this.$message.success(res.meta.msg)
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  }
}
</script>

<style scoped lang='less'>
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 120px;
}
</style>
